In [10]:
# ================================================================
# LAB 12. INFLUENTIAL DATA ANALYSIS
#
# STAT 415/615 - Regression
#
# Topics:
#   1. Leverage and the hat matrix
#   2. Regression estimates after deleting observations
#   3. Outlier detection using studentized residuals
#   4. Cook's distance
#   5. DFBETAS, DFFITS, and other influence measures
#
# ================================================================


# ================================================================
# PART 0. PREPARATION
# ================================================================

# Import the required libraries.
#
# pandas: data manipulation
# numpy: numerical calculations
# statsmodels: regression and influence diagnostics
# scipy: probability distributions and p-values
# matplotlib: graphs

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import statsmodels.api as sm

from scipy.stats import t


# Load the mtcars dataset.
#
# This is the same dataset used in Lab 11.
# It contains 32 automobiles and 11 variables.
#
# The first column contains automobile names.

mtcars = pd.read_csv(
    "https://raw.githubusercontent.com/vincentarelbundock/"
    "Rdatasets/master/csv/datasets/mtcars.csv",
    index_col=0
)


# Fit the full multiple regression model:
#
# mpg = beta0 + beta1*cyl + ... + beta10*carb + error

Y = mtcars["mpg"]

X = mtcars.drop(columns="mpg")

X = sm.add_constant(X)

reg = sm.OLS(Y, X).fit()


# Display the regression summary.

print(reg.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                    mpg   R-squared:                       0.869
Model:                            OLS   Adj. R-squared:                  0.807
Method:                 Least Squares   F-statistic:                     13.93
Date:                Wed, 28 Oct 2026   Prob (F-statistic):           3.79e-07
Time:                        16:51:51   Log-Likelihood:                -69.855
No. Observations:                  32   AIC:                             161.7
Df Residuals:                      21   BIC:                             177.8
Df Model:                          10                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
------------------------------------------------------------------------------
const         12.3034     18.718      0.657      0.518     -26.623      51.229
cyl           -0.1114      1.045     -0.107      0.916      -2.285       2.062
disp           0.0133      0.018      0.747      0.463      -0.024       0.050
hp            -0.0215      0.022     -0.987      0.335      -0.067       0.024
drat           0.7871      1.635      0.481      0.635      -2.614       4.188
wt            -3.7153      1.894     -1.961      0.063      -7.655       0.224
qsec           0.8210      0.731      1.123      0.274      -0.699       2.341
vs             0.3178      2.105      0.151      0.881      -4.059       4.694
am             2.5202      2.057      1.225      0.234      -1.757       6.797
gear           0.6554      1.493      0.439      0.665      -2.450       3.761
carb          -0.1994      0.829     -0.241      0.812      -1.923       1.524
==============================================================================
Omnibus:                        1.907   Durbin-Watson:                   1.861
Prob(Omnibus):                  0.385   Jarque-Bera (JB):                1.747
Skew:                           0.521   Prob(JB):                        0.418
Kurtosis:                       2.526   Cond. No.                     1.22e+04
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.22e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
In [12]:
# ================================================================
# PART 1. LEVERAGE AND THE HAT MATRIX
# ================================================================

# An observation may have an unusual combination of
# predictor values, even if its response is not unusual.
#
# Such observations are said to have high leverage.
#
# The hat matrix is:
#
#     H = X (X'X)^(-1) X'
#
# The diagonal elements Hii measure leverage.
#
# We do not need to calculate the entire hat matrix.
# statsmodels provides its diagonal directly.


# ------------------------------------------------
# 1A. Obtain the influence diagnostics
# ------------------------------------------------

# get_influence() calculates regression diagnostics
# for individual observations.
#
# This is similar to influence(reg) in R.

infl = reg.get_influence()


# Examine the leverage values.

leverage = infl.hat_matrix_diag

print("\nLEVERAGE VALUES")

print(
    pd.Series(
        leverage,
        index=mtcars.index,
        name="Leverage"
    ).round(4)
)


# ------------------------------------------------
# 1B. Mean leverage
# ------------------------------------------------

# In multiple regression with an intercept:
#
#     sum(Hii) = p + 1
#
# where p is the number of predictors.
#
# Therefore:
#
#     mean(Hii) = (p + 1) / n
#
# For mtcars:
#     p = 10 predictors
#     n = 32 observations
#
# Expected mean leverage = 11/32 = 0.34375.


n = len(Y)

p = X.shape[1] - 1

mean_leverage = (p + 1) / n

print("\nTHEORETICAL MEAN LEVERAGE:")
print(mean_leverage)

print("\nACTUAL MEAN LEVERAGE:")
print(np.mean(leverage))


# ------------------------------------------------
# 1C. Plot leverage values
# ------------------------------------------------

# Plot Hii against observation number.
#
# Observations with unusually large leverage
# may deserve further investigation.
#
# A commonly used screening threshold is
# twice the average leverage:
#
#     Hii > 2(p + 1)/n
#
# This is a rule of thumb, not a formal test.


plt.figure(figsize=(9, 5))

plt.scatter(
    range(1, n + 1),
    leverage
)

plt.axhline(
    mean_leverage,
    color="gray",
    linestyle="--",
    label="Mean leverage"
)

plt.axhline(
    2 * mean_leverage,
    color="red",
    linestyle="--",
    label="Twice mean leverage"
)

plt.xlabel("Observation number")
plt.ylabel("Leverage")
plt.title("Leverage Values")

plt.legend()
plt.grid(alpha=0.3)

plt.show()
LEVERAGE VALUES
rownames
Mazda RX4              0.3025
Mazda RX4 Wag          0.2902
Datsun 710             0.2388
Hornet 4 Drive         0.2277
Hornet Sportabout      0.1995
Valiant                0.2823
Duster 360             0.3259
Merc 240D              0.3302
Merc 230               0.7423
Merc 280               0.4293
Merc 280C              0.3749
Merc 450SE             0.3033
Merc 450SL             0.1921
Merc 450SLC            0.2237
Cadillac Fleetwood     0.3745
Lincoln Continental    0.3090
Chrysler Imperial      0.3067
Fiat 128               0.1790
Honda Civic            0.5119
Toyota Corolla         0.2329
Toyota Corona          0.4334
Dodge Challenger       0.2180
AMC Javelin            0.1744
Camaro Z28             0.4081
Pontiac Firebird       0.2053
Fiat X1-9              0.1422
Porsche 914-2          0.6232
Lotus Europa           0.4311
Ford Pantera L         0.6633
Ferrari Dino           0.3910
Maserati Bora          0.6428
Volvo 142E             0.2905
Name: Leverage, dtype: float64

THEORETICAL MEAN LEVERAGE:
0.34375

ACTUAL MEAN LEVERAGE:
0.34374999999999944
No description has been provided for this image
In [13]:
# ================================================================
# PART 2. DELETING INDIVIDUAL OBSERVATIONS
# ================================================================

# An observation is influential if removing it
# substantially changes the fitted regression model.
#
# We can examine what happens when each observation
# is deleted from the dataset.
#
# The influence diagnostics provide:
#
#   1. Regression coefficients without observation i.
#   2. Residual variance without observation i.
#
# These correspond to the quantities:
#
#     infl$coefficients
#     infl$sigma
#
# in the R lab.


# ------------------------------------------------
# 2A. Regression coefficients after deletion
# ------------------------------------------------

# params_not_obsi contains the regression coefficient
# estimates after deleting each observation.
#
# Each row corresponds to one deleted observation.
#
# Each column corresponds to a regression coefficient.


coefficients_deleted = pd.DataFrame(
    infl.params_not_obsi,
    index=mtcars.index,
    columns=X.columns
)

print("\nREGRESSION COEFFICIENTS AFTER DELETION")

print(coefficients_deleted.round(4))


# ------------------------------------------------
# 2B. Residual standard deviations after deletion
# ------------------------------------------------

# sigma2_not_obsi contains the estimated residual
# variance after deleting each observation.
#
# Taking the square root gives the residual
# standard deviation, or RMSE, of each reduced model.


sigma_deleted = pd.Series(
    np.sqrt(infl.sigma2_not_obsi),
    index=mtcars.index,
    name="RMSE after deletion"
)

print("\nRESIDUAL STANDARD DEVIATIONS AFTER DELETION")

print(sigma_deleted.round(4))
REGRESSION COEFFICIENTS AFTER DELETION
                       const     cyl    disp      hp    drat      wt    qsec  \
rownames                                                                       
Mazda RX4            13.8229 -0.1181  0.0151 -0.0272  0.7284 -3.9244  0.8327   
Mazda RX4 Wag        12.2036 -0.0771  0.0135 -0.0246  0.7821 -3.7417  0.8558   
Datsun 710           16.7974 -0.2512  0.0082 -0.0150  0.4908 -3.0070  0.6275   
Hornet 4 Drive       12.1962 -0.1130  0.0130 -0.0212  0.8117 -3.6900  0.8214   
Hornet Sportabout    12.5877 -0.1348  0.0115 -0.0206  0.7868 -3.4836  0.7892   
Valiant              12.5712  0.0264  0.0124 -0.0219  0.1454 -3.6565  0.8611   
Duster 360           12.5268 -0.1251  0.0135 -0.0213  0.7841 -3.7418  0.8193   
Merc 240D             8.8966  0.1422  0.0122 -0.0177  0.9301 -3.8719  0.9560   
Merc 230            -11.0555 -0.1363  0.0180 -0.0101  1.2246 -4.7812  1.9736   
Merc 280             12.3387 -0.1878  0.0142 -0.0200  0.6847 -3.8306  0.8809   
Merc 280C            10.2081  0.1221  0.0119 -0.0249  1.0551 -3.5563  0.7708   
Merc 450SE           12.4813 -0.3449  0.0235 -0.0268  0.7172 -4.5385  0.9155   
Merc 450SL           13.3742 -0.2549  0.0171 -0.0241  0.7916 -3.8494  0.7797   
Merc 450SLC          11.5442 -0.0544  0.0121 -0.0205  0.7899 -3.6809  0.8525   
Cadillac Fleetwood   11.9389 -0.2768  0.0197 -0.0266  0.6211 -3.8593  0.8972   
Lincoln Continental  12.3206 -0.1544  0.0140 -0.0220  0.7757 -3.6271  0.8180   
Chrysler Imperial    11.5543  0.1866  0.0166 -0.0262  0.2973 -5.0838  1.0147   
Fiat 128             15.9710 -0.3553  0.0184 -0.0248  0.6696 -4.2592  0.7424   
Honda Civic          13.0656 -0.1482  0.0112 -0.0191  0.5287 -3.5005  0.7967   
Toyota Corolla       22.0740 -0.4538  0.0116 -0.0238  0.4844 -3.1673  0.3651   
Toyota Corona        20.1990 -0.7301  0.0123 -0.0119  0.7638 -4.0380  0.7626   
Dodge Challenger     13.9343 -0.0468  0.0135 -0.0239  0.5398 -3.7836  0.7750   
AMC Javelin          10.7484  0.1378  0.0128 -0.0237  0.8410 -3.8459  0.8555   
Camaro Z28           12.3193 -0.1121  0.0133 -0.0215  0.7891 -3.7148  0.8203   
Pontiac Firebird     12.2839 -0.1094  0.0075 -0.0173  0.8358 -3.2932  0.7961   
Fiat X1-9            12.4027 -0.0911  0.0131 -0.0214  0.7842 -3.6957  0.8179   
Porsche 914-2        12.6401 -0.1571  0.0131 -0.0213  0.8164 -3.6668  0.8029   
Lotus Europa          2.9737  0.2068  0.0088 -0.0204  1.8422 -3.2420  1.1065   
Ford Pantera L      -13.6478  1.1658  0.0135 -0.0108  2.6920 -3.2065  0.9529   
Ferrari Dino         12.2897 -0.1109  0.0133 -0.0215  0.7891 -3.7150  0.8212   
Maserati Bora        14.5450 -0.0840  0.0125 -0.0283  1.1534 -3.3114  0.6389   
Volvo 142E           16.1568 -0.3035  0.0073 -0.0151  0.9073 -2.7504  0.5958   

                         vs      am    gear    carb  
rownames                                             
Mazda RX4            0.1077  2.8110  0.4034  0.0174  
Mazda RX4 Wag        0.1234  2.7912  0.5234 -0.0930  
Datsun 710           0.7065  3.2599  0.5068 -0.5260  
Hornet 4 Drive       0.2725  2.5146  0.6580 -0.2063  
Hornet Sportabout    0.3795  2.6061  0.6354 -0.2173  
Valiant              0.8275  2.8583  0.7688 -0.2469  
Duster 360           0.3142  2.5041  0.6337 -0.1911  
Merc 240D            0.3509  3.2882  0.3253 -0.2308  
Merc 230            -1.6337  1.7016  1.4834 -0.0596  
Merc 280             0.0695  2.6956  0.5829 -0.2083  
Merc 280C            0.8404  2.1538  0.8562 -0.1459  
Merc 450SE           0.5705  2.5374  0.6008  0.1215  
Merc 450SL           0.5522  2.5443  0.6665 -0.1091  
Merc 450SLC          0.2193  2.5304  0.6578 -0.2283  
Cadillac Fleetwood   0.3627  2.8755  0.5786  0.0047  
Lincoln Continental  0.3280  2.6179  0.6390 -0.1885  
Chrysler Imperial    0.3140  2.0736  0.8869  0.0483  
Fiat 128             0.0918  1.4262  0.7501  0.0696  
Honda Civic          0.1922  2.4552  0.8221 -0.3023  
Toyota Corolla       0.4104  1.4394  0.8786 -0.2217  
Toyota Corona       -0.1642  1.7619 -0.0490 -0.1414  
Dodge Challenger     0.3072  2.4427  0.7531 -0.2217  
AMC Javelin          0.1418  2.3593  0.7969 -0.2740  
Camaro Z28           0.3178  2.5184  0.6537 -0.1996  
Pontiac Firebird     0.3480  2.6290  0.5425 -0.2360  
Fiat X1-9            0.4024  2.6903  0.6051 -0.2218  
Porsche 914-2        0.1572  2.4185  0.7262 -0.2365  
Lotus Europa        -0.3911  3.0222  0.0378 -0.1730  
Ford Pantera L       1.2040  2.6977  2.9410 -1.2655  
Ferrari Dino         0.3188  2.5205  0.6550 -0.2001  
Maserati Bora        0.1472  2.1382  0.6989 -0.4198  
Volvo 142E           0.7632  3.2701  0.2732 -0.4482  

RESIDUAL STANDARD DEVIATIONS AFTER DELETION
rownames
Mazda RX4              2.6817
Mazda RX4 Wag          2.6996
Datsun 710             2.5676
Hornet 4 Drive         2.7153
Hornet Sportabout      2.7040
Valiant                2.6479
Duster 360             2.7155
Merc 240D              2.6654
Merc 230               2.6203
Merc 280               2.7116
Merc 280C              2.6870
Merc 450SE             2.6493
Merc 450SL             2.6825
Merc 450SLC            2.7122
Cadillac Fleetwood     2.6761
Lincoln Continental    2.7118
Chrysler Imperial      2.4696
Fiat 128               2.4639
Honda Civic            2.7109
Toyota Corolla         2.4739
Toyota Corona          2.6400
Dodge Challenger       2.6910
AMC Javelin            2.6432
Camaro Z28             2.7156
Pontiac Firebird       2.6418
Fiat X1-9              2.7050
Porsche 914-2          2.7151
Lotus Europa           2.5891
Ford Pantera L         2.4444
Ferrari Dino           2.7156
Maserati Bora          2.6866
Volvo 142E             2.5988
Name: RMSE after deletion, dtype: float64
In [14]:
# ================================================================
# PART 3. OUTLIER DETECTION
# ================================================================

# An outlier is an observation with an unusually
# large residual relative to its estimated variability.
#
# Externally studentized residuals are especially useful
# for detecting outliers.
#
# The externally studentized residual for observation i
# uses the residual variance estimated without
# observation i.
#
# Under the normal linear regression model, these
# residuals have a t-distribution with
#
#     n - p - 2
#
# degrees of freedom, where p is the number of slopes.
#
# We can use them to test whether an individual
# observation is an outlier.


# ------------------------------------------------
# 3A. Externally studentized residuals
# ------------------------------------------------

rstudent = infl.resid_studentized_external

print("\nEXTERNALLY STUDENTIZED RESIDUALS")

print(
    pd.Series(
        rstudent,
        index=mtcars.index,
        name="RStudent"
    ).round(4)
)


# ------------------------------------------------
# 3B. Outlier tests
# ------------------------------------------------

# For each observation, test:
#
#     H0: The observation follows the regression model.
#
# A two-sided p-value is calculated from the
# externally studentized residual.
#
# Since we test all n observations, we also calculate
# Bonferroni-adjusted p-values:
#
#     adjusted p-value = min(n * p-value, 1)
#
# This corresponds to outlierTest(reg) from R's
# car package.


df = int(reg.df_resid - 1)

pvalues = 2 * t.sf(
    np.abs(rstudent),
    df
)

pvalues_bonf = np.minimum(
    n * pvalues,
    1
)


outliers = pd.DataFrame({
    "RStudent": rstudent,
    "Unadjusted p": pvalues,
    "Bonferroni p": pvalues_bonf
}, index=mtcars.index)


# Display the observations with the smallest p-values.

print("\nOUTLIER TESTS")

print(
    outliers.sort_values("Unadjusted p").head(10)
)


# Display observations significant after Bonferroni
# correction at the 5% level.

print("\nBONFERRONI-SIGNIFICANT OUTLIERS")

print(
    outliers[
        outliers["Bonferroni p"] < 0.05
    ]
)
EXTERNALLY STUDENTIZED RESIDUALS
rownames
Mazda RX4             -0.7142
Mazda RX4 Wag         -0.4889
Datsun 710            -1.5404
Hornet 4 Drive         0.0681
Hornet Sportabout      0.4161
Valiant               -1.0177
Duster 360            -0.0387
Merc 240D              0.8729
Merc 230              -1.2172
Merc 280               0.2446
Merc 280C             -0.6551
Merc 450SE             1.0075
Merc 450SL             0.7053
Merc 450SLC           -0.2269
Cadillac Fleetwood    -0.7720
Lincoln Continental   -0.2380
Chrysler Imperial      2.0456
Fiat 128               2.0725
Honda Civic            0.2657
Toyota Corolla         2.0250
Toyota Corona         -1.0785
Dodge Challenger      -0.6064
AMC Javelin           -1.0544
Camaro Z28            -0.0029
Pontiac Firebird       1.0651
Fiat X1-9             -0.3965
Porsche 914-2         -0.0918
Lotus Europa           1.4152
Ford Pantera L        -2.1643
Ferrari Dino           0.0029
Maserati Bora          0.6594
Volvo 142E            -1.3560
Name: RStudent, dtype: float64

OUTLIER TESTS
                   RStudent  Unadjusted p  Bonferroni p
rownames                                               
Ford Pantera L    -2.164273      0.042719           1.0
Fiat 128           2.072513      0.051358           1.0
Chrysler Imperial  2.045632      0.054171           1.0
Toyota Corolla     2.024985      0.056426           1.0
Datsun 710        -1.540379      0.139141           1.0
Lotus Europa       1.415235      0.172383           1.0
Volvo 142E        -1.355985      0.190218           1.0
Merc 230          -1.217158      0.237712           1.0
Toyota Corona     -1.078480      0.293656           1.0
Pontiac Firebird   1.065100      0.299521           1.0

BONFERRONI-SIGNIFICANT OUTLIERS
Empty DataFrame
Columns: [RStudent, Unadjusted p, Bonferroni p]
Index: []
In [15]:
# ================================================================
# PART 4. COOK'S DISTANCE
# ================================================================

# Cook's distance measures the overall influence
# of an observation on the fitted regression model.
#
# It combines information about:
#
#   1. The size of the residual.
#   2. The leverage of the observation.
#
# A large Cook's distance indicates that deleting
# the observation substantially changes the fitted
# regression values.
#
# Unlike leverage alone, Cook's distance measures
# the combined effect of unusual predictors and
# an unusual response.


# ------------------------------------------------
# 4A. Calculate Cook's distance
# ------------------------------------------------

# cooks_distance returns Cook's distances and
# their associated reference p-values.
#
# We use the distances themselves.

cook = infl.cooks_distance[0]


cook = pd.Series(
    cook,
    index=mtcars.index,
    name="Cook's distance"
)

print("\nCOOK'S DISTANCES")

print(cook.round(4))


# ------------------------------------------------
# 4B. Plot Cook's distance
# ------------------------------------------------

plt.figure(figsize=(9, 5))

plt.scatter(
    range(1, n + 1),
    cook
)

plt.xlabel("Observation number")
plt.ylabel("Cook's distance")
plt.title("Cook's Distance")

plt.grid(alpha=0.3)

plt.show()


# ------------------------------------------------
# 4C. Identify observations with large Cook's distance
# ------------------------------------------------

# Following the original R lab, select observations
# with Cook's distance greater than 0.3.
#
# This threshold is used here for illustration;
# it is not a universal significance cutoff.

print("\nOBSERVATIONS WITH COOK'S DISTANCE > 0.3")

print(cook[cook > 0.3])
COOK'S DISTANCES
rownames
Mazda RX4              0.0206
Mazda RX4 Wag          0.0092
Datsun 710             0.0635
Hornet 4 Drive         0.0001
Hornet Sportabout      0.0041
Valiant                0.0370
Duster 360             0.0001
Merc 240D              0.0345
Merc 230               0.3792
Merc 280               0.0043
Merc 280C              0.0240
Merc 450SE             0.0401
Merc 450SL             0.0110
Merc 450SLC            0.0014
Cadillac Fleetwood     0.0331
Lincoln Continental    0.0024
Chrysler Imperial      0.1461
Fiat 128               0.0736
Honda Civic            0.0070
Toyota Corolla         0.0986
Toyota Corona          0.0803
Dodge Challenger       0.0096
AMC Javelin            0.0212
Camaro Z28             0.0000
Pontiac Firebird       0.0265
Fiat X1-9              0.0025
Porsche 914-2          0.0013
Lotus Europa           0.1317
Ford Pantera L         0.7135
Ferrari Dino           0.0000
Maserati Bora          0.0731
Volvo 142E             0.0658
Name: Cook's distance, dtype: float64
No description has been provided for this image
OBSERVATIONS WITH COOK'S DISTANCE > 0.3
rownames
Merc 230          0.379221
Ford Pantera L    0.713521
Name: Cook's distance, dtype: float64
In [16]:
# ================================================================
# PART 5. ADDITIONAL INFLUENCE MEASURES
# ================================================================

# Cook's distance summarizes the overall effect
# of deleting an observation.
#
# Other diagnostics examine particular aspects
# of that effect.
#
# DFBETAS:
#   Measures how much each regression coefficient
#   changes when observation i is deleted,
#   standardized by its estimated standard error.
#
# DFFITS:
#   Measures the change in the fitted value for
#   observation i when that observation is deleted.
#
# COVRATIO:
#   Measures the effect of deleting an observation
#   on the generalized variance of the estimated
#   regression coefficients.
#
# statsmodels calculates all of these quantities.


# ------------------------------------------------
# 5A. DFBETAS
# ------------------------------------------------

# There is one DFBETAS value for every observation
# and every regression coefficient.
#
# Large absolute values indicate that the observation
# has a substantial effect on that coefficient.


dfbetas = pd.DataFrame(
    infl.dfbetas,
    index=mtcars.index,
    columns=X.columns
)

print("\nDFBETAS")

print(dfbetas.round(3))


# ------------------------------------------------
# 5B. DFFITS
# ------------------------------------------------

# DFFITS measures the standardized change in the
# fitted value when an observation is removed.

dffits = pd.Series(
    infl.dffits[0],
    index=mtcars.index,
    name="DFFITS"
)

print("\nDFFITS")

print(dffits.round(3))


# ------------------------------------------------
# 5C. COVRATIO
# ------------------------------------------------

# COVRATIO compares the determinant of the covariance
# matrix of the coefficient estimates after deleting
# an observation with that of the full regression.
#
# Values substantially different from 1 may indicate
# influential observations.


covratio = pd.Series(
    infl.cov_ratio,
    index=mtcars.index,
    name="COVRATIO"
)

print("\nCOVRATIO")

print(covratio.round(3))


# ------------------------------------------------
# 5D. Combined influence diagnostics
# ------------------------------------------------

# statsmodels provides a convenient summary table
# containing several influence measures.
#
# This is similar to influence.measures(reg) in R.


influence_table = infl.summary_frame()

# Use automobile names as row labels.

influence_table.index = mtcars.index

print("\nINFLUENCE DIAGNOSTICS")

print(influence_table.round(3))


# ------------------------------------------------
# 5E. Display the most influential observations
# ------------------------------------------------

# Sort observations by Cook's distance.
#
# The table also includes leverage, externally
# studentized residuals, DFFITS, and COVRATIO.

summary = pd.DataFrame({
    "Leverage": leverage,
    "RStudent": rstudent,
    "Cook": cook,
    "DFFITS": dffits,
    "COVRATIO": covratio
}, index=mtcars.index)

print("\nMOST INFLUENTIAL OBSERVATIONS")

print(
    summary.sort_values(
        "Cook",
        ascending=False
    ).head(10).round(3)
)
DFBETAS
                     const    cyl   disp     hp   drat     wt   qsec     vs  \
rownames                                                                      
Mazda RX4           -0.080  0.006 -0.097  0.260  0.035  0.109 -0.016  0.099   
Mazda RX4 Wag        0.005 -0.032 -0.010  0.141  0.003  0.014 -0.047  0.091   
Datsun 710          -0.248  0.138  0.299 -0.305  0.187 -0.386  0.273 -0.191   
Hornet 4 Drive       0.006  0.001  0.016 -0.011 -0.015 -0.013 -0.000  0.021   
Hornet Sportabout   -0.015  0.022  0.102 -0.041  0.000 -0.120  0.043 -0.029   
Valiant             -0.014 -0.132  0.050  0.017  0.393 -0.031 -0.055 -0.242   
Duster 360          -0.012  0.013 -0.008 -0.007  0.002  0.014  0.002  0.002   
Merc 240D            0.181 -0.241  0.061 -0.175 -0.087  0.082 -0.184 -0.016   
Merc 230             1.262  0.024 -0.262 -0.528 -0.271  0.569 -1.595  0.938   
Merc 280            -0.002  0.071 -0.046 -0.067  0.061  0.060 -0.080  0.115   
Merc 280C            0.110 -0.220  0.077  0.156 -0.162 -0.083  0.068 -0.245   
Merc 450SE          -0.010  0.223 -0.567  0.243  0.043  0.435 -0.129 -0.120   
Merc 450SL          -0.057  0.136 -0.210  0.117 -0.003  0.070  0.056 -0.110   
Merc 450SLC          0.040 -0.053  0.068 -0.044 -0.002 -0.018 -0.042  0.046   
Cadillac Fleetwood   0.019  0.157 -0.353  0.234  0.101  0.075 -0.103 -0.021   
Lincoln Continental -0.001  0.040 -0.036  0.025  0.007 -0.045  0.004 -0.005   
Chrysler Imperial    0.043 -0.306 -0.195  0.232  0.321  0.775 -0.284  0.002   
Fiat 128            -0.211  0.251 -0.305  0.165  0.077  0.309  0.116  0.115   
Honda Civic         -0.040  0.034  0.116 -0.107  0.154 -0.111  0.033  0.058   
Toyota Corolla      -0.559  0.351  0.102  0.112  0.198 -0.310  0.668 -0.047   
Toyota Corona       -0.423  0.594  0.058 -0.443  0.014  0.171  0.080  0.230   
Dodge Challenger    -0.086 -0.061 -0.011  0.108  0.149  0.036  0.062  0.005   
AMC Javelin          0.083 -0.239  0.030  0.102 -0.033  0.069 -0.047  0.084   
Camaro Z28          -0.001  0.001  0.000 -0.001 -0.001 -0.000  0.001 -0.000   
Pontiac Firebird     0.001 -0.002  0.326 -0.195 -0.030 -0.224  0.034 -0.014   
Fiat X1-9           -0.005 -0.019  0.013 -0.004  0.002 -0.010  0.004 -0.039   
Porsche 914-2       -0.018  0.043  0.013 -0.009 -0.017 -0.025  0.024  0.074   
Lotus Europa         0.510 -0.312  0.260 -0.049 -0.660 -0.256 -0.400  0.345   
Ford Pantera L       1.503 -1.325 -0.008 -0.534 -1.263 -0.291 -0.196 -0.457   
Ferrari Dino         0.001 -0.000 -0.000 -0.000 -0.001 -0.000 -0.000 -0.000   
Maserati Bora       -0.118 -0.026  0.044  0.308 -0.221 -0.210  0.246  0.080   
Volvo 142E          -0.210  0.187  0.342 -0.300 -0.075 -0.519  0.314 -0.216   

                        am   gear   carb  
rownames                                  
Mazda RX4           -0.140  0.167 -0.259  
Mazda RX4 Wag       -0.129  0.087 -0.126  
Datsun 710          -0.371  0.103  0.407  
Hornet 4 Drive       0.003 -0.002  0.008  
Hornet Sportabout   -0.041  0.013  0.021  
Valiant             -0.165 -0.076  0.057  
Duster 360           0.008  0.014 -0.010  
Merc 240D           -0.371  0.220  0.038  
Merc 230             0.403 -0.561 -0.171  
Merc 280            -0.083  0.047  0.011  
Merc 280C            0.176 -0.133 -0.064  
Merc 450SE          -0.008  0.037 -0.387  
Merc 450SL          -0.012 -0.007 -0.108  
Merc 450SLC         -0.005 -0.002  0.034  
Cadillac Fleetwood  -0.171  0.051 -0.244  
Lincoln Continental -0.046  0.011 -0.013  
Chrysler Imperial    0.233 -0.166 -0.321  
Fiat 128             0.572 -0.068 -0.349  
Honda Civic          0.031 -0.109  0.121  
Toyota Corolla       0.563 -0.160  0.029  
Toyota Corona        0.370  0.474 -0.070  
Dodge Challenger     0.037 -0.064  0.026  
AMC Javelin          0.078 -0.095  0.090  
Camaro Z28           0.001  0.001  0.000  
Pontiac Firebird    -0.053  0.076  0.044  
Fiat X1-9           -0.081  0.033  0.026  
Porsche 914-2        0.048 -0.046  0.044  
Lotus Europa        -0.250  0.423 -0.033  
Ford Pantera L      -0.094 -1.659  1.395  
Ferrari Dino        -0.000  0.000  0.001  
Maserati Bora        0.183 -0.029  0.262  
Volvo 142E          -0.372  0.261  0.306  

DFFITS
rownames
Mazda RX4             -0.470
Mazda RX4 Wag         -0.313
Datsun 710            -0.863
Hornet 4 Drive         0.037
Hornet Sportabout      0.208
Valiant               -0.638
Duster 360            -0.027
Merc 240D              0.613
Merc 230              -2.066
Merc 280               0.212
Merc 280C             -0.507
Merc 450SE             0.665
Merc 450SL             0.344
Merc 450SLC           -0.122
Cadillac Fleetwood    -0.597
Lincoln Continental   -0.159
Chrysler Imperial      1.361
Fiat 128               0.968
Honda Civic            0.272
Toyota Corolla         1.116
Toyota Corona         -0.943
Dodge Challenger      -0.320
AMC Javelin           -0.485
Camaro Z28            -0.002
Pontiac Firebird       0.541
Fiat X1-9             -0.161
Porsche 914-2         -0.118
Lotus Europa           1.232
Ford Pantera L        -3.037
Ferrari Dino           0.002
Maserati Bora          0.885
Volvo 142E            -0.868
Name: DFFITS, dtype: float64

COVRATIO
rownames
Mazda RX4              1.859
Mazda RX4 Wag          2.115
Datsun 710             0.655
Hornet 4 Drive         2.209
Hornet Sportabout      1.943
Valiant                1.367
Duster 360             2.535
Merc 240D              1.693
Merc 230               3.024
Merc 280               2.900
Merc 280C              2.166
Merc 450SE             1.424
Merc 450SL             1.616
Merc 450SLC            2.142
Cadillac Fleetwood     1.979
Lincoln Continental    2.400
Chrysler Imperial      0.305
Fiat 128               0.245
Honda Civic            3.371
Toyota Corolla         0.287
Toyota Corona          1.621
Dodge Challenger       1.790
AMC Javelin            1.143
Camaro Z28             2.889
Pontiac Firebird       1.173
Fiat X1-9              1.829
Porsche 914-2          4.518
Lotus Europa           1.052
Ford Pantera L         0.502
Ferrari Dino           2.809
Maserati Bora          3.779
Volvo 142E             0.916
Name: COVRATIO, dtype: float64

INFLUENCE DIAGNOSTICS
                     dfb_const  dfb_cyl  dfb_disp  dfb_hp  dfb_drat  dfb_wt  \
rownames                                                                      
Mazda RX4               -0.080    0.006    -0.097   0.260     0.035   0.109   
Mazda RX4 Wag            0.005   -0.032    -0.010   0.141     0.003   0.014   
Datsun 710              -0.248    0.138     0.299  -0.305     0.187  -0.386   
Hornet 4 Drive           0.006    0.001     0.016  -0.011    -0.015  -0.013   
Hornet Sportabout       -0.015    0.022     0.102  -0.041     0.000  -0.120   
Valiant                 -0.014   -0.132     0.050   0.017     0.393  -0.031   
Duster 360              -0.012    0.013    -0.008  -0.007     0.002   0.014   
Merc 240D                0.181   -0.241     0.061  -0.175    -0.087   0.082   
Merc 230                 1.262    0.024    -0.262  -0.528    -0.271   0.569   
Merc 280                -0.002    0.071    -0.046  -0.067     0.061   0.060   
Merc 280C                0.110   -0.220     0.077   0.156    -0.162  -0.083   
Merc 450SE              -0.010    0.223    -0.567   0.243     0.043   0.435   
Merc 450SL              -0.057    0.136    -0.210   0.117    -0.003   0.070   
Merc 450SLC              0.040   -0.053     0.068  -0.044    -0.002  -0.018   
Cadillac Fleetwood       0.019    0.157    -0.353   0.234     0.101   0.075   
Lincoln Continental     -0.001    0.040    -0.036   0.025     0.007  -0.045   
Chrysler Imperial        0.043   -0.306    -0.195   0.232     0.321   0.775   
Fiat 128                -0.211    0.251    -0.305   0.165     0.077   0.309   
Honda Civic             -0.040    0.034     0.116  -0.107     0.154  -0.111   
Toyota Corolla          -0.559    0.351     0.102   0.112     0.198  -0.310   
Toyota Corona           -0.423    0.594     0.058  -0.443     0.014   0.171   
Dodge Challenger        -0.086   -0.061    -0.011   0.108     0.149   0.036   
AMC Javelin              0.083   -0.239     0.030   0.102    -0.033   0.069   
Camaro Z28              -0.001    0.001     0.000  -0.001    -0.001  -0.000   
Pontiac Firebird         0.001   -0.002     0.326  -0.195    -0.030  -0.224   
Fiat X1-9               -0.005   -0.019     0.013  -0.004     0.002  -0.010   
Porsche 914-2           -0.018    0.043     0.013  -0.009    -0.017  -0.025   
Lotus Europa             0.510   -0.312     0.260  -0.049    -0.660  -0.256   
Ford Pantera L           1.503   -1.325    -0.008  -0.534    -1.263  -0.291   
Ferrari Dino             0.001   -0.000    -0.000  -0.000    -0.001  -0.000   
Maserati Bora           -0.118   -0.026     0.044   0.308    -0.221  -0.210   
Volvo 142E              -0.210    0.187     0.342  -0.300    -0.075  -0.519   

                     dfb_qsec  dfb_vs  dfb_am  dfb_gear  dfb_carb  cooks_d  \
rownames                                                                     
Mazda RX4              -0.016   0.099  -0.140     0.167    -0.259    0.021   
Mazda RX4 Wag          -0.047   0.091  -0.129     0.087    -0.126    0.009   
Datsun 710              0.273  -0.191  -0.371     0.103     0.407    0.064   
Hornet 4 Drive         -0.000   0.021   0.003    -0.002     0.008    0.000   
Hornet Sportabout       0.043  -0.029  -0.041     0.013     0.021    0.004   
Valiant                -0.055  -0.242  -0.165    -0.076     0.057    0.037   
Duster 360              0.002   0.002   0.008     0.014    -0.010    0.000   
Merc 240D              -0.184  -0.016  -0.371     0.220     0.038    0.035   
Merc 230               -1.595   0.938   0.403    -0.561    -0.171    0.379   
Merc 280               -0.080   0.115  -0.083     0.047     0.011    0.004   
Merc 280C               0.068  -0.245   0.176    -0.133    -0.064    0.024   
Merc 450SE             -0.129  -0.120  -0.008     0.037    -0.387    0.040   
Merc 450SL              0.056  -0.110  -0.012    -0.007    -0.108    0.011   
Merc 450SLC            -0.042   0.046  -0.005    -0.002     0.034    0.001   
Cadillac Fleetwood     -0.103  -0.021  -0.171     0.051    -0.244    0.033   
Lincoln Continental     0.004  -0.005  -0.046     0.011    -0.013    0.002   
Chrysler Imperial      -0.284   0.002   0.233    -0.166    -0.321    0.146   
Fiat 128                0.116   0.115   0.572    -0.068    -0.349    0.074   
Honda Civic             0.033   0.058   0.031    -0.109     0.121    0.007   
Toyota Corolla          0.668  -0.047   0.563    -0.160     0.029    0.099   
Toyota Corona           0.080   0.230   0.370     0.474    -0.070    0.080   
Dodge Challenger        0.062   0.005   0.037    -0.064     0.026    0.010   
AMC Javelin            -0.047   0.084   0.078    -0.095     0.090    0.021   
Camaro Z28              0.001  -0.000   0.001     0.001     0.000    0.000   
Pontiac Firebird        0.034  -0.014  -0.053     0.076     0.044    0.026   
Fiat X1-9               0.004  -0.039  -0.081     0.033     0.026    0.002   
Porsche 914-2           0.024   0.074   0.048    -0.046     0.044    0.001   
Lotus Europa           -0.400   0.345  -0.250     0.423    -0.033    0.132   
Ford Pantera L         -0.196  -0.457  -0.094    -1.659     1.395    0.714   
Ferrari Dino           -0.000  -0.000  -0.000     0.000     0.001    0.000   
Maserati Bora           0.246   0.080   0.183    -0.029     0.262    0.073   
Volvo 142E              0.314  -0.216  -0.372     0.261     0.306    0.066   

                     standard_resid  hat_diag  dffits_internal  student_resid  \
rownames                                                                        
Mazda RX4                    -0.723     0.303           -0.476         -0.714   
Mazda RX4 Wag                -0.498     0.290           -0.318         -0.489   
Datsun 710                   -1.492     0.239           -0.836         -1.540   
Hornet 4 Drive                0.070     0.228            0.038          0.068   
Hornet Sportabout             0.425     0.200            0.212          0.416   
Valiant                      -1.017     0.282           -0.638         -1.018   
Duster 360                   -0.040     0.326           -0.028         -0.039   
Merc 240D                     0.878     0.330            0.616          0.873   
Merc 230                     -1.203     0.742           -2.042         -1.217   
Merc 280                      0.250     0.429            0.217          0.245   
Merc 280C                    -0.664     0.375           -0.514         -0.655   
Merc 450SE                    1.007     0.303            0.664          1.007   
Merc 450SL                    0.714     0.192            0.348          0.705   
Merc 450SLC                  -0.232     0.224           -0.125         -0.227   
Cadillac Fleetwood           -0.780     0.374           -0.603         -0.772   
Lincoln Continental          -0.244     0.309           -0.163         -0.238   
Chrysler Imperial             1.906     0.307            1.268          2.046   
Fiat 128                      1.927     0.179            0.900          2.073   
Honda Civic                   0.272     0.512            0.278          0.266   
Toyota Corolla                1.890     0.233            1.041          2.025   
Toyota Corona                -1.074     0.433           -0.940         -1.078   
Dodge Challenger             -0.616     0.218           -0.325         -0.606   
AMC Javelin                  -1.052     0.174           -0.483         -1.054   
Camaro Z28                   -0.003     0.408           -0.002         -0.003   
Pontiac Firebird              1.062     0.205            0.540          1.065   
Fiat X1-9                    -0.405     0.142           -0.165         -0.397   
Porsche 914-2                -0.094     0.623           -0.121         -0.092   
Lotus Europa                  1.383     0.431            1.204          1.415   
Ford Pantera L               -1.996     0.663           -2.802         -2.164   
Ferrari Dino                  0.003     0.391            0.002          0.003   
Maserati Bora                 0.668     0.643            0.897          0.659   
Volvo 142E                   -1.330     0.291           -0.851         -1.356   

                     dffits  
rownames                     
Mazda RX4            -0.470  
Mazda RX4 Wag        -0.313  
Datsun 710           -0.863  
Hornet 4 Drive        0.037  
Hornet Sportabout     0.208  
Valiant              -0.638  
Duster 360           -0.027  
Merc 240D             0.613  
Merc 230             -2.066  
Merc 280              0.212  
Merc 280C            -0.507  
Merc 450SE            0.665  
Merc 450SL            0.344  
Merc 450SLC          -0.122  
Cadillac Fleetwood   -0.597  
Lincoln Continental  -0.159  
Chrysler Imperial     1.361  
Fiat 128              0.968  
Honda Civic           0.272  
Toyota Corolla        1.116  
Toyota Corona        -0.943  
Dodge Challenger     -0.320  
AMC Javelin          -0.485  
Camaro Z28           -0.002  
Pontiac Firebird      0.541  
Fiat X1-9            -0.161  
Porsche 914-2        -0.118  
Lotus Europa          1.232  
Ford Pantera L       -3.037  
Ferrari Dino          0.002  
Maserati Bora         0.885  
Volvo 142E           -0.868  

MOST INFLUENTIAL OBSERVATIONS
                   Leverage  RStudent   Cook  DFFITS  COVRATIO
rownames                                                      
Ford Pantera L        0.663    -2.164  0.714  -3.037     0.502
Merc 230              0.742    -1.217  0.379  -2.066     3.024
Chrysler Imperial     0.307     2.046  0.146   1.361     0.305
Lotus Europa          0.431     1.415  0.132   1.232     1.052
Toyota Corolla        0.233     2.025  0.099   1.116     0.287
Toyota Corona         0.433    -1.078  0.080  -0.943     1.621
Fiat 128              0.179     2.073  0.074   0.968     0.245
Maserati Bora         0.643     0.659  0.073   0.885     3.779
Volvo 142E            0.291    -1.356  0.066  -0.868     0.916
Datsun 710            0.239    -1.540  0.064  -0.863     0.655
In [ ]:
# ================================================================
# PART 6. EXPORT THE NOTEBOOK TO HTML AND IPYNB
# ================================================================

# This section saves the current Google Colab notebook
# in two formats:
#
# HTML:
#   A readable document containing the Python code,
#   explanatory comments, tables, and graphical output.
#
# IPYNB:
#   An executable Jupyter notebook that can be opened
#   and edited in Google Colab or Jupyter.
#
# Run this section AFTER executing the previous cells,
# so that their output is included in the exported files.
#
# Both files will be downloaded to your computer.
# Your browser's download settings determine where
# they are saved.


from google.colab import _message, files
from nbconvert import HTMLExporter
import nbformat
import json


# Retrieve the current Colab notebook.

notebook = _message.blocking_request(
    "get_ipynb",
    timeout_sec=60
)["ipynb"]


# Convert to the standard Jupyter notebook format.

nb = nbformat.reads(
    notebook if isinstance(notebook, str)
    else json.dumps(notebook),
    as_version=4
)


# Specify a common filename for both versions.

filename = "Py Lab 12 - Influential Data Analysis"


# ------------------------------------------------
# Save the executable Jupyter notebook
# ------------------------------------------------

with open(filename + ".ipynb", "w", encoding="utf-8") as f:
    nbformat.write(nb, f)


# ------------------------------------------------
# Convert the notebook to HTML
# ------------------------------------------------

html, resources = HTMLExporter().from_notebook_node(nb)


# Save the HTML document.

with open(filename + ".html", "w", encoding="utf-8") as f:
    f.write(html)


# ------------------------------------------------
# Download both files
# ------------------------------------------------

files.download(filename + ".html")

files.download(filename + ".ipynb")


# ================================================================
# END OF LAB 12
# ================================================================
In [ ]: